package nio.socket.nonblocking;

import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Calendar;

/**
 * @Auther: luobiao
 * @Date: 2020/8/16 22:00
 * @Description:
 */
public class TimeServerHandleTask implements Runnable {
    SocketChannel socketChannel;

    public TimeServerHandleTask(SocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    @Override
    public void run() {
        try {
            ByteBuffer requestBuffer = ByteBuffer.allocate("GET CURRENT TIME".length());
            //尝试读取数据，因为是非阻塞，所以如果没有数据会立即返回。
            int bytesRead = socketChannel.read(requestBuffer);
            //如果没有读取到数据，说明当前SocketChannel并没有发送请求，不需要处理
            if (bytesRead <= 0) {
                return;
            }
            String timeStr = Calendar.getInstance().getTime().toLocaleString();
            ByteBuffer responseBuffer = ByteBuffer.allocate(timeStr.length());
            responseBuffer.put(timeStr.getBytes());
            responseBuffer.flip();
            socketChannel.write(responseBuffer);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
